﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading;

namespace Pahan.McuFusion.Common.Utils
{
    public class PriorityScope : IDisposable
    {
        public PriorityScope(ProcessPriorityClass processPriority, ThreadPriority threadPriority)
        {
            currentProcess = Process.GetCurrentProcess();
            prevProcessPriority = currentProcess.PriorityClass;
            prevThreadPriority = Thread.CurrentThread.Priority;
            currentProcess.PriorityClass = processPriority;
            Thread.CurrentThread.Priority = threadPriority;
        }
        
        public static PriorityScope Realtime
        {
            get
            {
                return new PriorityScope(ProcessPriorityClass.RealTime, ThreadPriority.Highest);
            }
        }

        #region Implementation of IDisposable

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <filterpriority>2</filterpriority>
        public void Dispose()
        {
            Thread.CurrentThread.Priority = prevThreadPriority;
            currentProcess.PriorityClass = prevProcessPriority;
        }

        #endregion

        private readonly Process currentProcess;

        private readonly ProcessPriorityClass prevProcessPriority;

        private readonly ThreadPriority prevThreadPriority;
    }
}
